// 假如选择了上传图片，就调用这个方法
// 传值_this, _this.data.maxUploadLen
import { renewOSSWx } from "../service/api/api-aliyun";
import { getApi } from './http';
import { getUUID } from './uuid';


var upFiles = (t, type, url, directory) => {
  if (type == "pictrue") {
    wx.chooseMedia({
      sourceType: ['camera'],
      success(res) {
        wx.showLoading({
          title: "上传中",
        })
        // var upPicturesArr = t.data.upPicturesArr || [];
        // let arr = res.tempFiles;
        // arr.map(function (v, i) {
        //   v['progress'] = 0;
        //   upPicturesArr.push(v)
        // })
        // t.setData({
        //   upPicturesArr
        // })
        var fileArr = t.data.upFileArr || [];
        // path:scr size progress:0
        let arr = res.tempFiles;
        // errMsg: "chooseImage:ok"
        // tempFilePaths: ["http://tmp/nG45akoAuMcQbdba9c4c3e8e9b037ab89035678d8e1d.png"]
        // tempFiles: [{…}]
        // console.log(res)
        arr.map(function (v, i) {
          v['progress'] = 0;
          v.name = '手机拍摄图片.jpg'
          fileArr.push(v)
        })

        // (imgArr)  0: {path: "http://tmp/b5LBAByigjh5bdba9c4c3e8e9b037ab89035678d8e1d.png", size: 3639, progress: 0}
        t.setData({
          upFileArr: fileArr
        })
        back(res, t, url, directory, type)
      }
    })
  } else {
    wx.chooseMessageFile({
      count: 10,
      type: type,
      // extension:type,
      extension: ['doc', 'docx', 'pdf', 'rar', 'zip', 'jpg', 'png', 'mp4'], //只保留这个扩展名的文件         
      async success(res) {
        wx.showLoading({
          title: "上传中",
        })
        var fileArr = t.data.upFileArr || [];
        // path:scr size progress:0
        let arr = res.tempFiles;
        // errMsg: "chooseImage:ok"
        // tempFilePaths: ["http://tmp/nG45akoAuMcQbdba9c4c3e8e9b037ab89035678d8e1d.png"]
        // tempFiles: [{…}]
        // console.log(res)
        arr.map(function (v, i) {
          v['progress'] = 0;
          fileArr.push(v)
        })
        // (imgArr)  0: {path: "http://tmp/b5LBAByigjh5bdba9c4c3e8e9b037ab89035678d8e1d.png", size: 3639, progress: 0}
        t.setData({
          upFileArr: fileArr
        })
        // console.log(typeof t); Object
        // console.log(t); route: "pages/index/index" __data__: {upFilesBtn: true, upFilesProgress: false, maxUploadLen: 6, __webviewId__: 14, upImgArr: Array(1)}
        // 获取 图片数组 和 视频数组 以及合并数组
        // let upFilesArr = getPathArr(t);
        // if (upFilesArr.length > count - 1) {
        //     let imgArr = t.data.upImgArr;
        //     let newimgArr = imgArr.slice(0, count)
        //     t.setData({
        //         upFilesBtn: false,
        //         upImgArr: newimgArr
        //     })
        // }
        back(res, t, url, directory, type)
      },
    });
  }

}
var back = async (res, t, url, directory, type) => {
  let combinedArr = [...t.data.upFileArr, ...t.data.upPicturesArr];
  t.setData({
    combinedArr: combinedArr
  });
  let file = ''
  let name = ''
  if (type == "pictrue") {
    file = res.tempFiles[0].tempFilePath;
    name = '手机拍摄图片.jpg'
  } else {
    file = res.tempFiles[0].path;
    name = res.tempFiles[0].name;
  }
  const extName = file.split('.').pop().toLocaleLowerCase();
  let mimeType = ""
  switch (extName) {
    case 'doc': mimeType = "application/msword"
      break;
    case 'docx': mimeType = "application/mswordapplication/vnd.openxmlformats-officedocument.wordprocessingml.document"
      break;
    case 'ppt': mimeType = "application/vnd.ms-powerpoint"
      break;
    case 'pptx': mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
      break;
    case 'xls': mimeType = "application/vnd.ms-excel"
      break;
    case 'xlsx': mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      break;
    case 'rar': mimeType = "application/rar"
      break;
    case 'zip': mimeType = "application/zip"
      break;
    case '7zip': mimeType = "application/zip"
      break;
    case 'pdf': mimeType = "application/pdf"
      break;
    case 'psd': mimeType = "application/x-photoshop"
      break;
    case 'wav': mimeType = "audio/x-wav"
      break;
    case 'mp3': mimeType = "audio/mpeg"
      break;
    case 'mp4': mimeType = "video/mp4"
      break;
    case 'txt': mimeType = "text/plain"
      break;
    case 'wps': mimeType = "application/kswps"
      break;
    case 'wpt': mimeType = "application/kswps"
      break;


    case 'dps': mimeType = "audio/x-wav"
      break;
    case 'dpt': mimeType = "audio/x-wav"
      break;
    case 'et': mimeType = "audio/x-wav"
      break;
    case 'ett': mimeType = "audio/x-wav"
      break;
  }


  //   /cues/topic/attachment/save
  //   /cues/submit/attachment/save
  //   /cues/active/attachment/save
  //   /instruct/
  //   /instruct/attachment/save

  const fileName = file.lastIndexOf('/'); //取到文件名开始到最后一个点的长度
  const fileNameLength = file.length; //取到文件名长度
  const fileFormat = file.substring(fileName + 1, fileNameLength); //截
  var newData = new Date()

  var y = newData.getFullYear(); //年份
  var m = newData.getMonth() + 1; //月份
  var d = newData.getDate(); //日期

  if (m >= 1 && m <= 9) {
    m = "0" + m;
  }
  if (d >= 1 && d <= 9) {
    d = "0" + d;
  }
  const date = y + "-" + m + "-" + d;
  const organizationName = t.data.currentUser.organizationName;
  const response = await renewOSSWx({
    // callbackUrl: `${getApi()}/cues/attachment/save`// 回调接口，选题计划和主动上报使用同一个
    callbackUrl: `${getApi()}${url}`// 回调接口，选题计划和主动上报使用同一个
  });
  if (response.code != 0) {
    return;
  }
  const uploadTask = wx.uploadFile({
    url: response.data.httpsBucket,
    filePath: file,
    name: 'file',
    formData: {
      key: `${organizationName}/${directory}/${date}/${name}`,
      policy: response.data.accessPolicy,
      OSSAccessKeyId: response.data.accessKeyId,
      signature: response.data.accessSignature,
      'x-oss-security-token': response.data.securityToken,
      'callback': response.data.callback,
      'success_action_status': '200',
    },
    header: {
      'Content-Disposition': 'attachment;',
      'Content-Type': mimeType,
    },
    success: (res) => {
      if (res.statusCode === 200) {
        wx.showToast({
          title: "上传成功",
          icon: "success"
        })

        let array = JSON.parse(res.data);
        const id = new Array();
        t.data.id.push(array.data.id)
      } else {
        wx.showToast({
          title: "上传失败"
        })
      }
    },
    fail: err => {
      wx.showToast({
        title: "图片上传失败"
      })
    }
  });
  uploadTask.onProgressUpdate((res) => {
    if (res.progress < 100) {
      wx.showLoading({
        mask: true,
        title: '上传中' + res.progress + '%',
      })
    }
    else {
      wx.hideLoading()
    };

  })
}

// 获取 图片数组 和 视频数组 以及合并数组
var getPathArr = t => {
  // 0: {path: "http://tmp/b5LBAByigjh5bdba9c4c3e8e9b037ab89035678d8e1d.png", size: 3639, progress: 0}
  let filearr = t.data.upFileArr || [];
  let upVideoArr = t.data.upVideoArr || [];
  let filePathArr = [];
  let videoPathArr = [];
  filearr.map(function (v, i) {
    filePathArr.push(v.path)
  })

  upVideoArr.map(function (v, i) {
    videoPathArr.push(v.tempFilePath)
  })
  // 连接数组imgPathArr和videoPathArr
  let filesPathsArr = filePathArr.concat(videoPathArr);
  return filesPathsArr;
}

module.exports = {
  upFiles,
  getPathArr,
}